package cn.huobi.pet.service.impl;

import cn.huobi.basic.config.BussinessException;
import cn.huobi.basic.domain.Point;
import cn.huobi.basic.service.impl.BaseServiceImpl;
import cn.huobi.basic.util.*;
import cn.huobi.order.domain.OrderPetAcquisition;
import cn.huobi.order.mapper.OrderPetAcquisitionMapper;
import cn.huobi.org.domain.Employee;
import cn.huobi.org.domain.Shop;
import cn.huobi.org.mapper.EmployeeMapper;
import cn.huobi.org.mapper.ShopMapper;
import cn.huobi.pet.domain.RejectSearchMasterLog;
import cn.huobi.pet.domain.SearchMasterMsg;
import cn.huobi.pet.domain.SearchMasterMsgAuditLog;
import cn.huobi.pet.dto.AcceptOrderDto;
import cn.huobi.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.huobi.pet.mapper.SearchMasterMsgMapper;
import cn.huobi.pet.query.SearchMasterMsgQuery;
import cn.huobi.pet.service.IRejectSearchMasterLogService;
import cn.huobi.pet.service.ISearchMasterMsgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huobi
 * @since 2022-11-01
 */
@Service
@Slf4j
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private IRejectSearchMasterLogService rejectSearchMasterLogService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer messageTimeOut;


    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        // 将数据存入数据库中
        searchMasterMsgMapper.add(searchMasterMsg);
        // 参数非空校验,审核失败添加审核日志
        parameterCheck(searchMasterMsg);
        // 百度AI审核内容,审核失败添加审核日志
        baiduAICheck(searchMasterMsg);
        // 审核成功，查询最近的店铺
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        List<Shop> shops = shopMapper.findAll();
        Shop nearestShop = DistanceUtil.getNearestShop(point, shops);
        // 判断是否查找到店铺
        if (nearestShop != null){
            searchMasterMsg.setShopId(nearestShop.getId());
        }
        // 修改审核状态，添加店铺id
        searchMasterMsg.setState(1);
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me().success();
    }

    @Override
    public PageList<SearchMasterMsg> seleteSearchMasterMsg(SearchMasterMsgQuery searchMasterMsg) {

        // 查询条数
        Integer totals = searchMasterMsgMapper.seleteSearchMasterMsgCount(searchMasterMsg);
        if(totals == null || totals == 0 ){
            return new PageList<>(0,new ArrayList<>());
        }
        // 根据页数查询相应条数数据
        List<SearchMasterMsg> searchMasterMsgs = searchMasterMsgMapper.seleteSearchMasterMsgPage(searchMasterMsg);
        return new PageList<>(totals,searchMasterMsgs);

    }

    /**
     * 接收订单
     */
    @Override
    public void accept(AcceptOrderDto acceptOrderDto) {
        // 根据id查询寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(acceptOrderDto.getMsgId());
        // 判断寻主消息是否为空
        if (searchMasterMsg == null){
            throw new BussinessException("寻主消息为空，请重新操作");
        }
        // 解决线程安全问题
        synchronized (searchMasterMsg.getId()){
            Employee employee = employeeMapper.findById(acceptOrderDto.getHandler());
            if (employee == null){
                throw new BussinessException("不存在此员工，请重新操作");
            }
            // 修改寻主消息状态
            if (searchMasterMsg.getState() == 1 && employee.getShopId().equals(searchMasterMsg.getShopId())){
                searchMasterMsg.setState(2);
                searchMasterMsgMapper.update(searchMasterMsg);
                // 生成收购单
                OrderPetAcquisition orderPetAcquisition = initOrderPetAcquisition(acceptOrderDto, searchMasterMsg, employee);

//                Message message = new Message("searchMaster_order_topic","order-delay-tag","寻主消息订单超时".getBytes(StandardCharsets.UTF_8));
//                message.setDelayTimeLevel(4);
                SendResult result = rocketMQTemplate.syncSend("searchMaster_order_topic",
                        MessageBuilder.withPayload(orderPetAcquisition.getId()).build(),
                        messageTimeOut, 4);
                log.info("消息发送结果：{}",result);
            }
        }
    }

    /**
     * 拒绝订单
     */
    @Override
    public void reject(AcceptOrderDto acceptOrderDto, Employee employee) {

        // 根据id查询寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(acceptOrderDto.getMsgId());
        // 判断寻主消息是否为空
        if (searchMasterMsg == null){
            throw new BussinessException("寻主消息为空，请重新操作");
        }
        // 将寻主消息shopId置空
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        // todo 记录拒单日志
        RejectSearchMasterLog rejectSearchMasterLog = new RejectSearchMasterLog();
        rejectSearchMasterLog.setEmpId(employee.getId());
        rejectSearchMasterLog.setMsgId(searchMasterMsg.getId());
        rejectSearchMasterLog.setNote(acceptOrderDto.getNote());
        rejectSearchMasterLogService.add(rejectSearchMasterLog);

    }

    /**
     * 生成订单
     */
    private OrderPetAcquisition initOrderPetAcquisition(AcceptOrderDto acceptOrderDto, SearchMasterMsg searchMasterMsg, Employee employee) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(acceptOrderDto.getHandler()));
        orderPetAcquisition.setDigest(acceptOrderDto.getNote());
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis()+ 3 * 24 * 60 * 60 * 1000));
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(employee.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(employee.getId());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisitionMapper.add(orderPetAcquisition);
        return orderPetAcquisition;
    }

    /**
     * 百度AI审核内容
     */
    private void baiduAICheck(SearchMasterMsg searchMasterMsg) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(searchMasterMsg.getTitle())
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getNote());
        if(!BaiduAuditUtils.TextCensor(stringBuilder.toString())){
            addAuditLog(searchMasterMsg,"信息涉及违规，审核失败，请在个人中心中进行修改发布");
            throw new BussinessException("信息涉及违规，审核失败，请在个人中心中进行修改发布");
        }
    }

    /**
     * 参数非空校验
     */
    private void parameterCheck(SearchMasterMsg searchMasterMsg) {
        if(StringUtils.isEmpty(searchMasterMsg.getTitle())){
            addAuditLog(searchMasterMsg,"寻主标题不能为空");
            throw new BussinessException("寻主标题不能为空");
        }
        if(StringUtils.isEmpty(searchMasterMsg.getName())){
            addAuditLog(searchMasterMsg,"宠物名称不能为空");
            throw new BussinessException("宠物名称不能为空");
        }
        if(StringUtils.isEmpty(searchMasterMsg.getAge())){
            addAuditLog(searchMasterMsg,"宠物年龄不能为空");
            throw new BussinessException("宠物年龄不能为空");
        }
        if(StringUtils.isEmpty(searchMasterMsg.getPrice())){
            addAuditLog(searchMasterMsg,"宠物不能为空");
            throw new BussinessException("宠物不能为空");
        }
        if(StringUtils.isEmpty(searchMasterMsg.getCoatColor())){
            addAuditLog(searchMasterMsg,"宠物毛色不能为空");
            throw new BussinessException("宠物毛色不能为空");
        }
        if(StringUtils.isEmpty(searchMasterMsg.getPetType())){
            addAuditLog(searchMasterMsg,"宠物品种不能为空");
            throw new BussinessException("宠物品种不能为空");
        }
        if(StringUtils.isEmpty(searchMasterMsg.getAddress())){
            addAuditLog(searchMasterMsg,"地址不能为空");
            throw new BussinessException("地址不能为空");
        }
    }

    /**
     * 审核日志添加
     */
    private void addAuditLog(SearchMasterMsg searchMasterMsg,String note) {
        SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
        searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
        searchMasterMsgAuditLog.setNote(note);
        searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
    }


}
